<?php

namespace App\Kuafu\Dashboard\Model;

use App\Kuafu\Config\Service\ConfigService;
use Illuminate\Support\Facades\Cache;

class Dashboard
{
    private $cache;

    public function __construct()
    {
        $this->cache = Cache::store('redis');
    }

    /**
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function getPage($pageName)
    {
        // 获取 rmsWeb 后台配置（pageVersion: 页面版本号, cdn: CDN 地址, baseUrl: API 地址）
        $config      = ConfigService::listByTypeAndKey("rmsWeb");
        $pageVersion = $config['pageVersion'];

        // 获取缓存页面
        $cacheKey = $this->getPageCacheKey($pageName, $pageVersion);

        //TODO: 开发过程去掉缓存
//        $pageContent = $this->cache->get($cacheKey);
        if (empty($pageContent)) {
            $pageUrl     = $config["cdn"] . $pageName . ".html?v=" . $pageVersion;
            $pageContent = file_get_contents($pageUrl);

            // 替换 CDN 路径
            $pageContent = str_replace('/static/', $config["cdn"], $pageContent);

            // 替换全局变量
            $pageContent = str_replace("BASE_URL", $config["baseUrl"], $pageContent);
            if (strlen($pageContent) > 0) {
                $this->cache->set($cacheKey, $pageContent);
            }
        }

        return $pageContent;
    }

    /**
     * 根据页面名称和版本获取缓存 KEY
     *
     * @param $pageName
     * @param $pageVersion
     * @return string
     */
    public function getPageCacheKey($pageName, $pageVersion): string
    {
        return "rmsWeb-{$pageName}-{$pageVersion}";
    }
}
